<template>
  <el-dialog
    v-bind="attrs"
    :visible.sync="dialogVisible"
    append-to-body
    :close-on-click-modal="false"
    :show-close="false"
    v-on="listeners"
  >
    <div class="search">
      <el-input
        v-model="params.keyword"
        :placeholder="placeholder"
        size="medium"
        clearable
      />

      <el-button
        type="primary"
        size="medium"
        @click="onSearch"
      >
        搜索
      </el-button>
    </div>
    <div class="list">
      <template v-if="!loading">
        <div
          v-for="item in list"
          :key="item.value"
          class="item"
          :class="{
            'item--selected': isSelected(item.value),
            'item--selected--disabled': isOldSelected(item.value) && choicesDisabled
          }"
          @click="handleChoose(item.value, item)"
        >
          {{ item.label }}
        </div>
      </template>

      <template v-else>
        <div
          v-loading="loading"
          style="height: 350px;"
        />
      </template>

    </div>
    <div class="page">
      <Pagination
        v-if="total"
        style="margin-top: 0; padding-bottom: 0;"
        :total="total"
        :limit.sync="params.pageSize"
        :page.sync="params.page"
        :pager-count="5"
        layout="total, prev, pager, next, jumper"
        @pagination="handlePageChange"
      />
    </div>

    <div class="footer">
      <el-button
        @click="handleCancel"
      >
        取消
      </el-button>

      <el-button
        type="primary"
        @click="handleConfirm"
      >
        确定
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
import Pagination from '@/components/Pagination/index.vue'
import { deepClone } from '@/utils'

export default {
  name: '',
  components: { Pagination },
  props: {
    value: {
      type: [String, Number, Array],
      default: ''
    },
    visible: {
      type: Boolean,
      required: true,
      default: false
    },
    list: {
      type: Array,
      default: () => []
    },
    total: {
      type: Number,
      default: 0
    },
    loading: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请输入'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    maxChoice: {
      type: Number,
      default: 3
    },
    choicesDisabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      params: {
        keyword: '',
        page: 1,
        pageSize: 10
      },
      valueBackup: null,
      valueMap: null
    }
  },
  computed: {
    attrs() {
      const attrs = { ...this.$attrs }
      return attrs
    },
    listeners() {
      const listeners = { ...this.$listeners }

      return listeners
    },
    dialogVisible: {
      get() {
        return this.visible
      },
      set(v) {
        this.$emit('update:visible', v)
      }
    }
  },
  watch: {
    visible(n) {
      if (n) {
        if (Array.isArray(this.value)) this.valueBackup = deepClone(this.value)
        else this.valueBackup = this.value
      }
    }
  },
  created() {
  },
  methods: {
    handlePageChange(e) {
      console.log('e --------->', e)
      this.params.page = e.page
      this.$emit('onPageChange', e.page, this.params.keyword)
    },

    onSearch() {
      this.params.page = 1

      this.$emit(
        'onSearch',
        {
          page: this.params.page,
          keyword: this.params.keyword
        })
    },

    isSelected(value) {
      if (Array.isArray(this.value) && this.value.length > 0) {
        const index = this.value.findIndex(item => item === value)
        return index !== -1
      } else if (typeof value === 'string' || typeof value === 'number') {
        return this.value === value
      } else {
        return false
      }
    },

    isOldSelected(value) {
      if (Array.isArray(this.valueBackup) && this.valueBackup.length > 0) {
        const index = this.valueBackup.findIndex(item => item === value)
        return index !== -1
      } else if (typeof value === 'string' || typeof value === 'number') {
        return this.valueBackup === value
      } else {
        return false
      }
    },

    handleChoose(value, item) {
      console.log('value --------->', value, item)
      if (this.isOldSelected(value) && this.choicesDisabled) return

      if (this.multiple) {
        if (this.isSelected(value)) {
          this.removeItem(value)
        } else {
          if (this.value.length >= this.maxChoice) return this.$message.error(`最多可选${this.maxChoice}个`)
          const val = [...this.value]
          val.push(value)
          // const valMap = this.valueMap ? [...this.valueMap] : []
          // valMap.push(item)
          // this.valueMap = valMap
          this.$emit('input', val)
        }
      } else {
        if (this.isSelected(value)) {
          this.valueMap = null
          this.$emit('input', null)
        } else {
          this.valueMap = item
          this.$emit('input', value)
        }
      }
    },

    removeItem(value) {
      const index = this.value.findIndex(item => item === value)
      // const index2 = this.valueMap.findIndex(item => item.value === value)
      if (index !== -1) {
        const val = [...this.value]
        val.splice(index, 1)
        this.$emit('input', val)
      }

      // if (index2 !== -1) {
      //   const val = [...this.valueMap]
      //   val.splice(index, 1)
      // }
    },

    handleCancel() {
      this.$emit('input', this.valueBackup)
      this.close()
    },

    handleConfirm() {
      console.log('this.valueMap --------->', this.valueMap)
      this.$emit('onConfirm', this.value, this.valueMap)
      this.close()
    },

    close() {
      this.params = this.$options.data().params
      this.$emit('update:visible', false)
    }
  }
}
</script>
<style lang="scss" scoped>
.list {
  padding: 0 20px;

  .item {
    padding: 10px;
    margin-bottom: 10px;
    background-color: #f5f5f5;
    border-radius: 5px;
    cursor: pointer;
    box-sizing: border-box;
    &--selected {
      background-color: #ECF5FF;
      border: 1px solid #409EFF;

      &--disabled {
        opacity: .5;
        cursor: not-allowed;
      }
    }
  }
}

.search{
  display: flex;
  padding: 0 20px;
  margin-bottom: 10px;
  .el-button {
    margin-left: 10px;
  }
}

.page {
  display: flex;
  justify-content: end;
  padding-bottom: 20px;
}

.footer {
  display: flex;
  justify-content: end;
  padding: 20px;
}

::v-deep(.el-dialog__body) {
  padding: 0;
}
</style>
